/**
 *  用来和后台交互
 *  @param {Object}     一个对象里面传各种属性
 *      key: url            value: {String}
 *      key: type           value: {String}
 *      key: data           value: {Object}
 *      key: success        value: {Function}
 *      key: error          value: {Function}
 **/

function ajax(options) {
    if (!options.url) return

    if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Miscrosoft.XMLHTTP')
    } else {
        var xhr = new XMLHttpRequest()
    }

    options.type = options.type || 'GET'

    // {key : value} => key=value&xxx
    let arr= []

    for (let attr in options.data) {
        arr.push(attr + '=' + options.data[attr])
    }

    let str = arr.join('&')

    if (options.type.toUpperCase() === 'GET') {
        xhr.open('GET', options.url + '?' + str, true)
        xhr.send()
    } else {
        xhr.open('POST', options.url, true)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(str)
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                options.success && options.success(xhr.responseText)
            } else {
                options.error && options.error(xhr.status)
            }
        }
    }
 }

function pAjax(options) {
    return new Promise(function (resolve, reject) {
        ajax({
            url: options.url,
            data: options.data,
            type: options.type,
            success: function (res) {
                resolve(res)
            },
            error: function (err) {
                reject(err)
            }
        })
    })
}